package com.test.study.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.logging.Logger;

/**
 * SQL 注入的demo 类
 * @author huyong
 *
 */
public class UserLoginDemo {
	private static final Logger LOGGER = Logger.getLogger(UserLoginDemo.class.getName());

	public boolean login(String username, String password) {
		Connection connection = null;
		Statement statement = null;
		ResultSet resultSet = null;
		try {
			connection = JdbcUtils.getConnection();
			String sql = "select * from user_test where username='" + username + "' and password='" + password + "'";
			LOGGER.info("sql == > "+sql);
			statement = connection.createStatement();
			resultSet = statement.executeQuery(sql);
			if (resultSet.next()) {
				return true;
			}
		} catch (Exception e) {
			LOGGER.info(e.getMessage());
			return false;
		} finally {
			JdbcUtils.close(connection, statement, resultSet);
		}
		return false;
	}
	
	public boolean login2(String username, String password) {
		Connection connection = null;
		PreparedStatement statement = null;
		ResultSet resultSet = null;
		try {
			connection = JdbcUtils.getConnection();
			String sql = "select * from user_test where username=? and password=?";
			statement = connection.prepareStatement(sql);
			statement.setString(1, username);
			statement.setString(2, password);
			LOGGER.info("sql == > "+sql);
			resultSet = statement.executeQuery();
			if (resultSet.next()) {
				return true;
			}
		} catch (Exception e) {
			LOGGER.info(e.getMessage());
			return false;
		} finally {
			JdbcUtils.close(connection, statement, resultSet);
		}
		return false;
	}

}
